package com.aramis.mydytt.ui.search

import android.os.Bundle
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.aramis.mydytt.R
import com.aramis.mydytt.ext.commonStartMovieDetailListener
import com.aramis.mydytt.ext.logE
import com.aramis.mydytt.ui.base.BaseActivity
import com.aramis.mydytt.ui.common.CommonMovieItemAdapter
import com.aramis.mydytt.widget.LoadingStateView
import com.aramis.mydytt.widget.SearchBar
import com.aramis.mydytt.widget.SearchHistoryView

/**
 * Description: SearchResultActivity
 * 搜索结果页
 * @author lizhidan
 * Created: 2021/4/8
 */
class SearchResultActivity : BaseActivity() {
    private lateinit var viewModel: SearchResultViewModel
    private lateinit var searchBar: SearchBar
    private lateinit var searchHistoryView: SearchHistoryView
    private lateinit var loadingStateView: LoadingStateView
    private val commonMovieItemAdapter = CommonMovieItemAdapter()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel = createViewModel()
        setContentView(R.layout.activity_search_result)
        initView()
        initData()
    }

    private fun search(key: String?) {
        logE("搜索key:$key")
        if (key != null && key.isNotBlank()) {
            searchHistoryView.visibility = View.GONE
            loadingStateView.showLoading()
            viewModel.search(key)
            val manager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            manager.hideSoftInputFromWindow(searchBar.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        } else {
            Toast.makeText(this, "搜索内容不存在，请检查", Toast.LENGTH_SHORT).show()
        }
    }

    private fun initData() {
        viewModel.searchLiveData.observe(this, {
            if (it == null || it.isEmpty()) {
                loadingStateView.showEmpty()
            } else {
                loadingStateView.dismiss()
            }
            commonMovieItemAdapter.setData(it)
        })
    }

    private fun initView() {
        searchBar = findViewById(R.id.search_bar_main)
        searchBar.onSearchClickListener = {
            search(it)
        }
        val recyclerView: RecyclerView = findViewById(R.id.list_search_result)
        recyclerView.adapter = commonMovieItemAdapter
        commonMovieItemAdapter.onItemClickListener = commonStartMovieDetailListener()
        recyclerView.layoutManager = GridLayoutManager(this, 3)

        searchHistoryView = findViewById(R.id.view_search_history)
        searchHistoryView.setHistory(viewModel.getSearchHistory())
        searchHistoryView.onItemClickListener = {
            search(it)
        }
        loadingStateView = findViewById(R.id.view_lading)
    }

}